package gossip.v2.cluster;

import com.baidu.bjf.remoting.protobuf.annotation.ProtobufClass;
import lombok.Getter;
import lombok.Setter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

// Gossip节点
@Getter
@Setter
@ProtobufClass
public class GossipNode {
    private String nodeId;
    private String ip;
    private int port;
    private volatile long lastHeartbeat;
    private transient ConcurrentMap<String, Long> versionVector = new ConcurrentHashMap<>();
    private transient volatile boolean isLocal = false;

    public GossipNode() {
    }

    public GossipNode(String nodeId, String ip, int port) {
        this.nodeId = nodeId;
        this.ip = ip;
        this.port = port;
    }

    public void updateLastHeartbeat() {
        lastHeartbeat = System.currentTimeMillis();
    }

    public void updateHeartbeat(long heartbeatTime) {
        lastHeartbeat = heartbeatTime;
    }

    public void updateVersion(String key, long version) {
        versionVector.put(key, version);
    }

    public Map<String, Long> getVersionVector() {
        return new ConcurrentHashMap<>(versionVector);
    }

    public void setLocal(boolean local) {
        isLocal = local;
    }

    @Override
    public String toString() {
        return "GossipNode{" +
                "nodeId='" + nodeId + '\'' +
                ", ip='" + ip + '\'' +
                ", port=" + port +
                ", isLocal=" + isLocal +
                '}';
    }
}
